package com.lzb.findphone.fragment;

import static androidx.core.content.ContextCompat.startForegroundService;

import static com.blankj.utilcode.util.ServiceUtils.startService;
import static com.blankj.utilcode.util.ServiceUtils.stopService;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.os.VibratorManager;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.lzb.findphone.BaseNoModelFragment;
import com.lzb.findphone.activity.MoreSoundActivity;
import com.lzb.findphone.R;
import com.lzb.findphone.adapter.HomeSoundAdapter;
import com.lzb.findphone.bean.SettingBean;
import com.lzb.findphone.bean.SoundBean;
import com.lzb.findphone.databinding.FragmentHomeBinding;
import com.lzb.findphone.dialog.PermissionExplainDialog;
import com.lzb.findphone.dialog.TipDialog;
import com.lzb.findphone.service.ClapDetectionService;
import com.lzb.findphone.utils.AppSpUtils;
import com.lzb.findphone.utils.FlashlightUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link HomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HomeFragment extends BaseNoModelFragment<FragmentHomeBinding> implements View.OnClickListener, OnItemClickListener {

    private HomeSoundAdapter soundAdapter;
    private List<SoundBean> listShow = new ArrayList<>();
    private int oldPosition;
    private boolean isOpen;

    @Override
    protected int onCreate() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        mDataBinding.ivTip.setOnClickListener(this);
        mDataBinding.ivSwitch.setOnClickListener(this);
        mDataBinding.llMore.setOnClickListener(this);

        mDataBinding.rvSoundList.setLayoutManager(new GridLayoutManager(mContext, 3));
        soundAdapter = new HomeSoundAdapter();
        mDataBinding.rvSoundList.setAdapter(soundAdapter);
        soundAdapter.setOnItemClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.ivTip) {//提示
            showTipDialog();
        } else if (id == R.id.ivSwitch) {//开关
            if (isOpen) {
                stop();
            } else {
                getPermission();
            }
        } else if (id == R.id.llMore) {//查看更多
            startActivity(MoreSoundActivity.class);
        }
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        soundAdapter.getItem(oldPosition).setSelected(false);
        oldPosition = position;
        soundAdapter.getItem(position).setSelected(true);
        soundAdapter.notifyDataSetChanged();
        SettingBean settingBean = AppSpUtils.getSetting();
        settingBean.setRing(soundAdapter.getItem(position).getRawId());
        AppSpUtils.saveSetting(settingBean);
        ToastUtils.showShort(getString(R.string.apply_suc));
    }

    @Override
    protected void initData() {
        FlashlightUtils.getInstance().init(mContext);

        listShow.add(new SoundBean(R.drawable.icon_dog, R.drawable.icon_dog2, "狗", R.raw.gou, false));
        listShow.add(new SoundBean(R.drawable.icon_police, R.drawable.icon_police2, "警察", R.raw.jingcha, false));
        listShow.add(new SoundBean(R.drawable.icon_cattle, R.drawable.icon_cattle2, "牛", R.raw.niu, false));
        listShow.add(new SoundBean(R.drawable.icon_sheep, R.drawable.icon_sheep2, "羊", R.raw.yang, false));
        listShow.add(new SoundBean(R.drawable.icon_frog, R.drawable.icon_frog2, "青蛙", R.raw.qingwa, false));
        listShow.add(new SoundBean(R.drawable.icon_pig, R.drawable.icon_pig2, "猪", R.raw.zhu, false));
        listShow.add(new SoundBean(R.drawable.icon_goast, R.drawable.icon_goast2, "鬼", R.raw.gui, false));
        listShow.add(new SoundBean(R.drawable.icon_baby, R.drawable.icon_baby2, "婴儿", R.raw.yinger, false));
        listShow.add(new SoundBean(R.drawable.icon_car, R.drawable.icon_car2, "卡车", R.raw.kache, false));
    }

    @Override
    public void onResume() {
        super.onResume();
        SettingBean settingBean = AppSpUtils.getSetting();
        for (int i = 0; i < listShow.size(); i++) {
            SoundBean soundBean = listShow.get(i);
            if (settingBean.getRing().equals(soundBean.getRawId())) {
                listShow.get(oldPosition).setSelected(false);
                oldPosition = i;
                listShow.get(i).setSelected(true);
                break;
            }
        }
        soundAdapter.setList(listShow);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            SettingBean settingBean = AppSpUtils.getSetting();
            for (int i = 0; i < listShow.size(); i++) {
                SoundBean soundBean = listShow.get(i);
                if (settingBean.getRing().equals(soundBean.getRawId())) {
                    listShow.get(oldPosition).setSelected(false);
                    oldPosition = i;
                    listShow.get(i).setSelected(true);
                    break;
                }
            }
            soundAdapter.setList(listShow);
        }
    }

    private void getPermission() {
        PermissionExplainDialog dialog = new PermissionExplainDialog(mContext);
        dialog.setContent(getString(R.string.get_record_permission));
        PermissionUtils.permission(Manifest.permission.RECORD_AUDIO).explain(new PermissionUtils.OnExplainListener() {
            @Override
            public void explain(@NonNull UtilsTransActivity activity, @NonNull List<String> denied, @NonNull ShouldRequest shouldRequest) {
                dialog.show();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        shouldRequest.start(true);
                    }
                }, 500);
            }
        }).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {
                dialog.dismiss();
                start();
            }

            @Override
            public void onDenied() {
                dialog.dismiss();
            }
        }).request();
    }

    private void start() {
        Intent serviceIntent = new Intent(getContext(), ClapDetectionService.class);
        startService(serviceIntent);
        isOpen = true;
        mDataBinding.ivSwitch.setImageResource(R.drawable.on);
        mDataBinding.rlSwitchBg.setBackgroundResource(R.drawable.open_bg);
        mDataBinding.tvSwitch.setText(getString(R.string.click_close));
    }

    private void stop() {
        Intent serviceIntent = new Intent(getContext(), ClapDetectionService.class);
        stopService(serviceIntent);
        isOpen = false;
        mDataBinding.ivSwitch.setImageResource(R.drawable.off);
        mDataBinding.rlSwitchBg.setBackgroundResource(R.drawable.close_bg);
        mDataBinding.tvSwitch.setText(getString(R.string.click_open));
    }

    private void showTipDialog() {
        TipDialog dialog = new TipDialog(mContext);
        dialog.show();
    }
}